package main

import (
	_ "embed"
	"eyecare/lib"
	"fmt"
	"net/url"
	"path"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"

	"github.com/getlantern/systray"
	"github.com/go-toast/toast"
)

const (
	APP_TITLE = "EyeCare"
)

// runtime status
var working = true
var pause = false
var fullscreen = false
var reminded = false

// GUI component
var myApp fyne.App = app.New()
var window fyne.Window = myApp.NewWindow(APP_TITLE)
var countdown = widget.NewLabel("")
var button *widget.Button

//go:embed images/logo_256.ico
var logo []byte

var icon = path.Join(lib.Dir, "images", "logo_128.ico")

var settings = lib.LoadSettings()
var expireTime = time.Now().Add(time.Minute * time.Duration(settings.WorkTime))

func main() {

	button = widget.NewButton("Pause", func() {
		pause = !pause
		toggleButtonText()
	})

	window.SetIcon(fyne.NewStaticResource("logo", logo))
	window.Resize(fyne.NewSize(320, 120))
	window.SetFixedSize(true)
	window.SetPadded(true)
	window.SetContent(container.NewVBox(
		countdown,
		button,
		widget.NewButton("Hide", window.Hide),
		widget.NewButton("About", func() {
			link, _ := url.Parse("https://eyecare.refusea.com")
			myApp.OpenURL(link)
		}),
	))

	go systray.Run(onReady, onExit)

	go func() {
		ticker := time.NewTicker(time.Second)
		defer ticker.Stop()
		for range ticker.C {
			care()
		}
	}()

	myApp.Run()
}

func care() {

	if !pause && settings.FullscreenDetermine {
		fullscreen, _ = lib.Determine()
	}

	if pause || fullscreen {
		expireTime = expireTime.Add(time.Second)
		return
	}

	minute, second := lib.Remain(expireTime)
	var status string
	if working {
		status = "Working, will break in %02d:%02d"
	} else {
		status = "Breaking, will work in %02d:%02d"
	}
	countdown.SetText(fmt.Sprintf(status, minute, second))

	var tooltip string
	if working {
		tooltip = "工作中"
	} else {
		tooltip = "休息中"
	}
	systray.SetTooltip(fmt.Sprintf("%s: ⏰ %02d:%02d", tooltip, minute, second))

	if !working {
		if minute == 0 && second == 0 {
			expireTime = time.Now().Add(time.Minute * time.Duration(settings.WorkTime))
			working = true
			reminded = false
			window.Hide()
		} else {
			window.CenterOnScreen()
			window.Show()
		}
		return
	}

	if minute == 0 && second > 0 && second < settings.RemindTime && !reminded {
		notify(true)
		reminded = true
		return
	}

	if minute == 0 && second == 0 {
		expireTime = time.Now().Add(time.Minute * time.Duration(settings.BreakTime))
		working = false
		window.CenterOnScreen()
		window.Show()
	}
}

func toggleButtonText() {
	if pause {
		button.SetText("Resume countdown")
	} else {
		button.SetText("Pause countdown")
	}
}

func onReady() {

	systray.SetIcon(logo)
	systray.SetTitle(APP_TITLE)

	mOpen := systray.AddMenuItem("Open", "Open")
	mStartUp := systray.AddMenuItemCheckbox("Run at Startup", "Run at Startup", settings.StartupStatus)
	systray.AddSeparator()
	mQuit := systray.AddMenuItem("Quit", "Quit")

	go func() {
		for {
			select {
			case <-mOpen.ClickedCh:
				window.CenterOnScreen()
				window.Show()
			case <-mStartUp.ClickedCh:
				settings.ToggleStartupStatus()
				if settings.StartupStatus {
					mStartUp.Check()
				} else {
					mStartUp.Uncheck()
				}
			case <-mQuit.ClickedCh:
				systray.Quit()
			}
		}
	}()

	if settings.StartupNotify {
		notify(false)
	}
}

func onExit() {
	myApp.Quit()
}

func notify(remind bool) {

	var title, message string
	if remind {
		title = "✅ 护眼提醒"
		message = fmt.Sprintf("🔔 已用眼 %d 分钟了，该休息了 🛌", settings.WorkTime)
	} else {
		title = "✅ 护眼就绪"
		message = fmt.Sprintf("👁️ EyeCare 开始保护 🛡️ 你的视力\n🔔 %d 分钟后将提醒你休息", settings.WorkTime)
	}

	n := &toast.Notification{
		AppID:   "👀 EyeCare",
		Title:   title,
		Message: message,
		Icon:    icon,
	}
	n.Push()
}
